/*
 * pre_proc_test.c
 *
 *  Created on: 19 jul 2012
 *      Author: Tiberiu S. Petre
 */

/*
 * dev_dsp_tc.c
 *
 *  Created on: Jul 13, 2012
 *      Author: Tiberiu S. Petre
 */

#define LENGTH 3    /* how many seconds of speech to store */
#define RATE 8000   /* the sampling rate */
#define SIZE 16      /* sample size: 8 or 16 bits */
#define CHANNELS 1  /* 1 = mono 2 = stereo */
#define BUFF_LENGTH (LENGTH * RATE * SIZE * CHANNELS/16)
#define NOF_HFRAMES ((BUFF_LENGTH/160) + (BUFF_LENGTH%160!=0))
#define GSM_BUFF_LENGTH NOF_HFRAMES*160

/* this buffer holds the digitized audio */
int16_t in_buf[GSM_BUFF_LENGTH];
int16_t out_buf[GSM_BUFF_LENGTH];

int16_t* in_pcm_frame;
int16_t in_frame_buf[160];

int16_t* out_pcm_frame;
int16_t out_frame_buf[160];

unpacked_hf uhf;

int pre_proc_test() {
	int fd; /* sound device file descriptor */
	int arg; /* argument for ioctl calls */
	int status; /* return status of system calls */
	int i;

	/* open sound device */
	fd = open("/dev/dsp", O_RDWR);
	if (fd < 0) {
		perror("open of /dev/dsp failed");
		exit(1);
	}

	/* set sampling parameters */
	arg = SIZE; /* sample size */
	status = ioctl(fd, SOUND_PCM_WRITE_BITS, &arg);
	if (status == -1)
		perror("SOUND_PCM_WRITE_BITS ioctl failed");
	if (arg != SIZE)
		perror("unable to set sample size");

	arg = CHANNELS; /* mono or stereo */
	status = ioctl(fd, SOUND_PCM_WRITE_CHANNELS, &arg);
	if (status == -1)
		perror("SOUND_PCM_WRITE_CHANNELS ioctl failed");
	if (arg != CHANNELS)
		perror("unable to set number of channels");

	arg = RATE; /* sampling rate */
	status = ioctl(fd, SOUND_PCM_WRITE_RATE, &arg);
	if (status == -1)
		perror("SOUND_PCM_WRITE_WRITE ioctl failed");

	arg = AFMT_S16_BE; /* sampling rate */
	status = ioctl(fd, SNDCTL_DSP_SETFMT, &arg);
	if (status == -1)
		perror("SNDCTL_DSP_SETFMT ioctl failed");

	while (1) { /* loop until Control-C */
		create_unpacked_hf(uhf);
		printf("Say something:\n");
		status = read(fd, in_buf, sizeof(in_buf)); /* record some sound */
		if (status != sizeof(in_buf))
			perror("read wrong number of bytes");

		// Encode and decode
		for (i = 0; i < NOF_HFRAMES; i++) {
			in_pcm_frame = in_buf + (i * 160);
			out_pcm_frame = out_buf + (i * 160);

			gsm_quantize(in_pcm_frame, in_frame_buf, 160);

			gsm_dequantize(out_frame_buf, out_pcm_frame, 160);
		}

//		fxp_to_file(in_buf,GSM_BUFF_LENGTH,"in_buf.txt");
//		fxp_to_file(out_buf,GSM_BUFF_LENGTH,"out_buf.txt");

		printf("You said:\n");
		status = write(fd, out_buf, sizeof(out_buf)); /* play it back */
		if (status != sizeof(out_buf))
			perror("wrote wrong number of bytes");
		/* wait for playback to complete before recording again */
		status = ioctl(fd, SOUND_PCM_SYNC, 0);
		if (status == -1)
			perror("SOUND_PCM_SYNC ioctl failed");
		destroy_unpacked_hf(uhf);
	}
}






